package com.animallife.android.ui;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.animallife.android.R;
import com.animallife.android.adapters.AnimalAdapter;
import com.animallife.android.billing.BuyItemActivity;
import com.animallife.android.db.AnimalColumns;
import com.animallife.android.db.AnimalQuery;
import com.animallife.android.model.Animals;
import com.animallife.android.util.Config;
import com.animallife.android.util.NotifyingAsyncQueryHandler;
import com.animallife.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.flurry.android.FlurryAgent;

public class AnimalListActivity extends Activity implements AsyncQueryListener, OnItemClickListener, ListView.OnScrollListener,
		OnClickListener {

	private final class RemoveWindow implements Runnable {
		public void run() {
			removeWindow();
		}
	}

	private NotifyingAsyncQueryHandler asyncHandler;
	private ListView listView;
	private AnimalAdapter adapter;
	private boolean mShowing;
	private RemoveWindow mRemoveWindow = new RemoveWindow();
	Handler mHandler = new Handler();
	private WindowManager mWindowManager;
	private TextView mDialogText;
	private boolean mReady;
	private char mPrevLetter = Character.MIN_VALUE;
	public static String selectionArgs = null;
	// private Cursor mCursor;
	// private boolean isSearchActive = false;
	private Button filter;
	private ImageButton search;

	public void onStart() {
		super.onStart();
		FlurryAgent.onStartSession(this, "CJVA21QV9JQKNUQS93F9");
	}

	public void onStop() {
		super.onStop();
		FlurryAgent.onEndSession(this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		listView = (ListView) findViewById(R.id.animals_list);
		listView.setOnItemClickListener(this);

		LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = mInflater.inflate(R.layout.header, null);
		listView.addHeaderView(view);
		filter = (Button) view.findViewById(R.id.clear_filter);
		search = (ImageButton) view.findViewById(R.id.button_search);
		filter.setOnClickListener(this);
		search.setOnClickListener(this);

		asyncHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		int animal_type = 0;
		Bundle bundle = getIntent().getExtras();
		if (bundle != null && bundle.containsKey(Config.ANIMAL_TYPE))
			animal_type = getIntent().getIntExtra(Config.ANIMAL_TYPE, 0);

		switch (animal_type) {
		case Config.REPTILES_TOKEN:
			selectionArgs = Config.REPTILIA;
			break;
		case Config.BIRD_TOKEN:
			selectionArgs = Config.BIRD;
			break;
		case Config.MAMMALIA_TOKEN:
			selectionArgs = Config.MAMMALIA;
			break;

		default:
			break;
		}

		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		listView.setOnScrollListener(this);

		LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		mDialogText = (TextView) inflate.inflate(R.layout.list_position, null);
		mDialogText.setVisibility(View.INVISIBLE);

		mHandler.post(new Runnable() {

			public void run() {
				mReady = true;
				WindowManager.LayoutParams lp = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION,
						WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
						PixelFormat.TRANSLUCENT);
				mWindowManager.addView(mDialogText, lp);
			}
		});

		showResult(selectionArgs, null);
	}

	private void showResult(String animal_class, String mask) {
		filter.setVisibility(View.VISIBLE);
		Uri uri = Animals.CONTENT_URI;
		String selection = AnimalColumns.ANIMAL_CLASS + " = '" + animal_class + "'";
		if (mask != null)
			selection = selection + " AND " + AnimalColumns.NAME.getName() + " like '%" + mask + "%'";
		asyncHandler.startQuery(AnimalQuery._TOKEN, uri, AnimalQuery.PROJECTION, selection, null, Animals.NAME_SORT);
	}

	private void showResultsById(String id) {
		filter.setVisibility(View.VISIBLE);
		asyncHandler.startQuery(AnimalQuery._TOKEN, Animals.CONTENT_URI, AnimalQuery.PROJECTION, AnimalColumns._ID.getName()
				+ " = " + id, null, Animals.NAME_SORT);
	}

	private void showResultsByIdOnIyemClick(String id) {
		filter.setVisibility(View.VISIBLE);
		asyncHandler.startQuery(AnimalQuery._TOKEN_BY_ID, Animals.CONTENT_URI, AnimalQuery.PROJECTION,
				AnimalColumns._ID.getName() + " = " + id, null, Animals.NAME_SORT);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		handleIntent(intent);
	}

	private void handleIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			// isSearchActive = true;
			showResult(selectionArgs, query);
		} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
			showResultsById(intent.getData().getLastPathSegment());

		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mReady = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		removeWindow();
		mReady = false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mWindowManager.removeView(mDialogText);
		mReady = false;
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case AnimalQuery._TOKEN:
			if (cursor != null) {
				startManagingCursor(cursor);
				// mCursor = cursor;
				if (null == adapter) {
					adapter = new AnimalAdapter(AnimalListActivity.this, cursor);
					listView.setAdapter(adapter);
				} else {
					adapter.changeCursor(cursor);
					adapter.notifyDataSetChanged();
				}
			}
			break;
		case AnimalQuery._TOKEN_BY_ID:

			Intent intent = null;
			int isAvalible = 0;
			if (cursor != null && cursor.moveToFirst()) {
				isAvalible = cursor.getInt(AnimalQuery.ISAVAILABLE);
			}

			switch (isAvalible) {
			case 1:
				intent = new Intent(getApplicationContext(), DetailActivity.class);
				intent.putExtra(Config._ID, cursor.getLong(AnimalQuery._ID));
				intent.putExtra(Config.ANIMAL_TYPE, selectionArgs);
				break;
			case 0:
				intent = new Intent(getApplicationContext(), BuyItemActivity.class);
				break;
			default:
				break;
			}

			startActivity(intent);

			break;

		default:
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		showResultsByIdOnIyemClick(String.valueOf(id));
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// if (mReady) {
		// TextView v = (TextView) view.findViewById(R.id.item_title);
		// char firstLetter = v.getText().charAt(0);
		//
		// if (!mShowing && firstLetter != mPrevLetter) {
		//
		// mShowing = true;
		// mDialogText.setVisibility(View.VISIBLE);
		// }
		// mDialogText.setText(((Character) firstLetter).toString());
		// mHandler.removeCallbacks(mRemoveWindow);
		// mHandler.postDelayed(mRemoveWindow, 3000);
		// mPrevLetter = firstLetter;
		// }

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

		TextView v = (TextView) view.findViewById(R.id.item_title);
		if (v != null) {
			char firstLetter = v.getText().charAt(0);
			if (!mShowing && firstLetter != mPrevLetter) {

				mShowing = true;
				mDialogText.setVisibility(View.VISIBLE);
			}
			mDialogText.setText(((Character) firstLetter).toString());
			mHandler.removeCallbacks(mRemoveWindow);
			mHandler.postDelayed(mRemoveWindow, 3000);
			mPrevLetter = firstLetter;

		}
	}

	private void removeWindow() {
		if (mShowing) {
			mShowing = false;
			mDialogText.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_search:
			this.startSearch(null, false, Bundle.EMPTY, false);
			break;
		case R.id.clear_filter:
			showResult(selectionArgs, null);
			break;
		default:
			break;
		}

	}

}